package pl.wroc.uni.ii.puzzle.data;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateAdapter implements JsonSerializer<Date>,
		JsonDeserializer<Date> {

	@Override
	public Date deserialize(JsonElement json, Type typeOfT,
			JsonDeserializationContext ctx) throws JsonParseException {
		JsonElement jsonPrimitive = json.getAsJsonPrimitive();
		if (jsonPrimitive == null) {
			throw new JsonParseException("jsonPrimitive is null");
		}
		Long milis = Long.parseLong(jsonPrimitive.getAsString());
		return new Date(milis);
	}

	@Override
	public JsonElement serialize(Date date, Type typeOfT,
			JsonSerializationContext ctx) {
		DateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
		dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		return new JsonPrimitive(dateFormat.format(date));
	}

}
